#!/usr/bin/env bash

# Retrieves OpenBSD official mirrors, ranks them based on speed
# License: CC0

MIRROR_HTML='/tmp/openbsd-mirrors.html'
TESTFILE="/doc/obsd-faq.txt"
TIMEOUT=10
BYTES=300000 # 300KB

if [ ! -f "$MIRROR_HTML" ]; then
	curl -L -o "$MIRROR_HTML" 'https://www.openbsd.org/ftp.html' && echo "== Downloaded mirrors html to: $MIRROR_HTML"
else
	echo "== Found previously downloaded mirrors html: $MIRROR_HTML"
fi

echo '== Checking HTTP(s) and FTP mirror speeds...'
echo '== This may take a long time...'
MIRRORS="$(sed -ne 's|.*href=\"\(.*:\/\/.*\/pub/OpenBSD\).*|\1|p' "$MIRROR_HTML")"
# rsync mirrors - not yet supported
#MIRRORS+="
#$(sed -ne 's|.*\(rsync:\/\/.*\/\).*|\1|p' "$MIRROR_HTML")"
MIRROR_TIME=''
MIRROR_TOTAL=$(echo "$MIRRORS" | wc -l | awk '{print $1}')
declare -i MIRROR_COUNT

for MIRROR in $MIRRORS
do
	MIRROR_COUNT+=1
	time=$(curl -r 0-$BYTES --max-time $TIMEOUT --fail --silent --output /dev/null --write-out %{time_total} ${MIRROR}${TESTFILE})
	if [ $? -eq 0 ]; then
		echo -n " [${MIRROR_COUNT}/${MIRROR_TOTAL}] ${MIRROR} = ${time}" $'\r'
		MIRROR_TIME+="
 ${MIRROR} = ${time}"
	else
		echo -n " [${MIRROR_COUNT}/${MIRROR_TOTAL}] ${MIRROR} = [FAIL]" $'\r'
	fi
done
echo -n "-- Finished testing --" $'\r'

echo '== Here are the about 10 fastest mirrors:'
echo "$MIRROR_TIME" | sort -n -k 3 | head -n 10

echo ''
echo '== You can use these in /etc/installurl or use in PKG_PATH env var:'
echo ' $ export PKG_PATH=ftp://your.ftp.mirror/pub/OpenBSD/`uname -r`/packages/`machine -a`/'
